package com.xmmj.baselibrary.utils.websocket

import kotlin.jvm.JvmOverloads
import org.java_websocket.client.WebSocketClient
import org.java_websocket.drafts.Draft_6455
import org.java_websocket.handshake.ServerHandshake
import java.lang.Exception
import java.net.URI

/**
 * WebSocket客户端
 */
open class JWebSocketClient @JvmOverloads constructor(uri: URI, debug: Boolean = true) :
    WebSocketClient(uri, Draft_6455()) {
    /**
     * 是否调试模式
     */
    private var isDebug = true

    /**
     * TAG标签
     */
    private var mTag: String? = WSLog.LOG_TAG

    init {
        mTag = mTag + "(" + uri.port + "-" + hashCode() + ")"
        isDebug = debug
    }

    override fun onOpen(serverHandshake: ServerHandshake) {
        log("onOpen()")
    }

    override fun onMessage(message: String) {
        log("onMessage() = $message")
    }

    override fun onClose(code: Int, reason: String, remote: Boolean) {
        log("onClose()")
    }

    override fun onError(ex: Exception) {
        log("onError() = $ex")
    }

    private fun log(msg: String) {
        if (isDebug) {
            WSLog.log(mTag, msg)
        }
    }

    fun setDebug(debug: Boolean) {
        isDebug = debug
    }
}